/**
 *  \file   flash_allocation.c
 *  \author Miora ANDRIAMANOHARISOA, Loic MINGHETTI
 *  \date   PFE 2011
 **/

#include "include.h"


/*************************************************************
 			IDENTIFICATION DU NOEUD
*************************************************************/

unsigned int NODE_ID;  
unsigned int HOP_COUNT; 
int OFFSET; 

#define FLASH_NODE_ID INFOD_START
#define FLASH_HOP_COUNT INFOD_START+2
#define FLASH_OFFSET INFOD_START+3

void save_segment_D() {
  flash_erase_segment((unsigned int *) INFOD_START);
  if(flash_write_word((unsigned int *) FLASH_NODE_ID, NODE_ID) != 0) {
    printf("\r\n(!) Failed writing to segment D\r\n");
  }
  if(flash_write_word((unsigned int *) FLASH_HOP_COUNT, HOP_COUNT) != 0) {
    printf("\r\n(!) Failed writing to segment D\r\n");
  }
  if(flash_write_word((unsigned int *) FLASH_OFFSET, OFFSET) != 0) {
    printf("\r\n(!) Failed writing to segment D\r\n");
  }
}

void flash_save_node_id() {
	unsigned int * saved = (unsigned int *) (FLASH_NODE_ID);
	if (*saved != NODE_ID) save_segment_D();
}

void flash_save_hop_count() {
	unsigned int * saved = (unsigned int *) (FLASH_HOP_COUNT);
	if ( *saved != HOP_COUNT) save_segment_D();
}

void flash_save_sensor_offset() {
	unsigned int * saved = (unsigned int *) (FLASH_OFFSET);
	if (*saved != OFFSET) save_segment_D();
}

void flash_allocation_init(void) {
	NODE_ID = *((unsigned int *) FLASH_NODE_ID);
	HOP_COUNT = *((unsigned int *) FLASH_HOP_COUNT);
	OFFSET = *((signed int *) FLASH_OFFSET);
}

